<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="45%"
      v-dialogDrag
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        v-loading="formLoading"
        label-width="100px"
      >
        <el-form-item label="用户" prop="memberUserId">
          <el-autocomplete
            clearable
            style="width: 100%"
            v-model="nickname"
            :fetch-suggestions="querySearchAsync"
            value-key="nickname"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusoptions"
              :key="parseInt(dict.value)"
              :label="dict.label"
              :value="parseInt(dict.value)"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="活动封面" prop="cover">
          <el-upload
            :action="actionUrl"
            :headers="headers"
            :show-file-list="false"
            class="avatar-uploader"
            :before-upload="beforeImageUpload"
            :on-success="handleUploadSuccess"
          >
            <img v-if="formData.cover" :src="formData.cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              支持 bmp/png/jpeg/jpg/gif 格式，大小不超过 2M
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="案例内容">
          <Editor v-model="formData.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="formData.publishTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:00"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as UserCaseApi from "@/api/ai/usercase";
import * as memberApi from "@/api/member";
import { getAccessToken } from "@/utils/auth";
import Editor from "@/components/Editor";
import { DICT_TYPE, getDictDatas } from "@/utils/dict";
export default {
  name: "UserCaseForm",
  components: {
    Editor,
  },
  data() {
    var validateMember = (rule, value, callback) => {
      if (!value || !this.nickname) {
        return callback(new Error("用户不能为空"));
      } else {
        callback();
      }
    };
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        memberUserId: undefined,
        title: undefined,
        cover: undefined,
        content: undefined,
        // status: 1,
        publishTime: undefined,
      },
      headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      actionUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload",
      statusoptions: getDictDatas(DICT_TYPE.Usercase_Status),
      // 表单校验
      timeout: null,
      nickname: undefined,
      formRules: {
        memberUserId: [
          { validator: validateMember, trigger: "blur", required: true },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        cover: [{ required: true, message: "封面不能为空", trigger: "blur" }],
        content: [
          { required: true, message: "案例内容不能为空", trigger: "blur" },
        ],
        publishTime: [
          { required: true, message: "发布时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleUploadSuccess(res) {
      console.log("resxxxx", res);
      this.formData.cover = res.data;
    },
    beforeImageUpload(file) {
      // 校验格式
      const isType =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif" ||
        file.type === "image/bmp" ||
        file.type === "image/jpg";
      if (!isType) {
        this.$message.error("上传图片格式不对!");
        return false;
      }
      // 校验大小
      const isLt = file.size / 1024 / 1024 < 2;
      if (!isLt) {
        this.$message.error("上传图片大小不能超过 2M!");
        return false;
      }
      return true;
    },
    handleSelect(item) {
      console.log("item", item);

      this.formData.memberUserId = item.id;
    },

    async querySearchAsync(queryString, cb) {
      let queryParams = {
        pageNo: 1,
        pageSize: 100,
        nickname: queryString,
      };
      const res = await memberApi.getMemberList(queryParams);
      var restaurants = res.data.list;
      // var restaurants = this.memberList;
      console.log("restaurants", restaurants);
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.nickname.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;

      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await UserCaseApi.getUserCase(id);
          this.formData = res.data;
          this.nickname = res.data.memberUserNickname;
          this.title = "修改用户案例";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.title = "新增用户案例";
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await UserCaseApi.updateUserCase(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit("success");
          return;
        }
        // 添加的提交
        await UserCaseApi.createUserCase(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit("success");
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        memberUserId: undefined,
        title: undefined,
        cover: undefined,
        content: undefined,
        // status: 1,
        publishTime: undefined,
      };
      this.resetForm("formRef");
    },
  },
};
</script>
<style lang="scss" scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
